package service

import (
	"eznat/core"
	"github.com/zserge/lorca"
	"log"
	"runtime"
)

type UIService struct {
	ChannelService *ChannelService
	EventBus       chan interface{}
}

func NewUI() *UIService {
	this := new(UIService)
	this.ChannelService = NewChannelService()
	return this
}
func (ui *UIService) Start() {
	var args []string
	if runtime.GOOS == "linux" {
		args = append(args, "--class=Lorca")
	}
	uiService, err := lorca.New("http://nwct.istiny.cc/dist", "", 1300, 600, args...)
	if err != nil {
		log.Fatal(err)
	}
	uiService.Eval(`
		console.log("Hello, world!");
		console.log('Multiple values:', [1, false, {"x":5}]); 
	`)

	uiService.Bind("start", ui.StartNatService)
	uiService.Bind("stop", ui.StopNatService)
	uiService.Bind("setConfig", ui.SetConfig)
	uiService.Bind("getConfig", ui.GetConfig)
	uiService.Bind("getStatus", ui.NatServiceStatus)
	uiService.Bind("getChannelStatus", func() int {
		return ui.ChannelService.ChannelServiceStatus
	})

	defer uiService.Close()
	<-uiService.Done()
}

func (ui *UIService) GetConfig() *core.Config {
	return core.NewConfig().GetConfig()
}
func (ui *UIService) SetConfig(value interface{}) {
	core.Config{}.Save(value)
	log.Println("创建/修改配置!")
}

func (ui *UIService) StartNatService() {
	ui.ChannelService.Stop()
	ui.ChannelService = NewChannelService()
	ui.ChannelService.Start()
}

func (ui *UIService) NatServiceStatus() int {
	return ui.ChannelService.ServiceStatus
}
func (ui *UIService) StopNatService() {
	ui.ChannelService.Stop()
}